<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/landCenter/fuelCardManagement">加油卡管理</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>加油卡明细</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <!-- 数据区 -->
      <a-row :gutter="[48]">
        <a-col :span="8">
          <div id="liquidFill" style="width:100%;height:150px;"></div>
        </a-col>
        <a-col :span="8">
          <div class="ant-card-body1">
            <div class="caiG1">
              <p class="caiGou">充值总金额（元）</p>
              <h1 class="cgYoul">{{truckOilCardInfo.rechargeAmount}}</h1>
            </div>
            <p class="cgSale">&nbsp;</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="ant-card-body1">
            <div class="caiG2">
              <p class="caiGou">消费总金额（元）</p>
              <h1 class="cgYoul">{{truckOilCardInfo.usedAmount}}</h1>
            </div>
            <p class="cgSale">
              油量（L）
              <span>{{truckOilCardInfo.usedOilVolume}}</span>
            </p>
          </div>
        </a-col>
      </a-row>
      <!-- 搜索 -->
      <a-form layout="inline" ref="form" :style="'margin-top:60px;'">
        <a-form-item label="加油卡">
          <a-select
            class="selectInputWidth"
            show-search
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            v-model="searchForm.cardId"
            @search="handleOilCardChange"
          >
            <a-select-option key>全部</a-select-option>
            <a-select-option v-for="d in oilCardLikeData" :key="d.cardId">{{ d.cardNo }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属公司">
          <a-input v-model="searchForm.custName" />
        </a-form-item>
        <a-form-item label="车辆">
          <a-input v-model="searchForm.truckNumber" />
        </a-form-item>
        <a-form-item label="日期">
          <a-range-picker @change="onChangeDate" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSubmit1">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="createRecord">+ 添加记录</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="exportExcel">导出Excel</a-button>
        </a-form-item>
      </a-form>
      <!-- 表格数据 -->
      <a-tabs @change="tabChange" :tab-bar-style="{margin:'20px 0 0 0'}">
        <a-tab-pane :key="1" tab="油卡充值" style="padding:0"></a-tab-pane>
        <a-tab-pane :key="2" tab="加油消费" style="padding:0"></a-tab-pane>
      </a-tabs>
      <a-row>
        <a-col :span="24">
          <a-table
            :columns="column"
            :loading="loading"
            :data-source="tableData"
            :pagination="pagination"
            :scroll="scroll"
            row-key="batchNo"
          >
            <template slot="detail" slot-scope="record">
              <a @click="viewDetail(record.detailId)">查看详情</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 新增记录modal -->
    <a-modal
      :visible="visible"
      title="新增记录"
      :body-style="{padding:'24px 40px 0px 20px'}"
      width="640px"
      centered
      :destroyOnClose="true"
      @ok="handleAdd"
      @cancel="handleCancel"
    >
      <a-row>
        <a-col :span="23" offset="1">
          <a-form-model
            ref="rulesForm"
            :model="form"
            :rules="formRules"
            :label-col="{span:8}"
            :wrapper-col="{span:16}"
          >
            <a-col :span="20">
              <a-form-model-item label="记录类型">
                <a-radio-group v-model="businessType" @change="handleChangeBusinessType">
                  <a-radio :value="1">油卡充值</a-radio>
                  <a-radio :value="2">加油消费</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>

            <a-col :span="20">
              <template v-if="isbusinessType1">
                <a-form-model-item label="加油卡卡号" prop="cardId">
                  <a-select
                    v-model="m"
                    show-search
                    :show-arrow="false"
                    :filter-option="false"
                    :default-active-first-option="false"
                    :not-found-content="null"
                    @search="handleOilCardChangeModal"
                    @select="handleOilCardSelect"
                  >
                    <a-select-option
                      v-for="(d) in oilCardLikeDataModal"
                      :key="d.cardId"
                    >{{ d.cardNo }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-col :span="24">
                  <a-col :span="8">
                    <p class="descData">所属公司：</p>
                  </a-col>
                  <a-col :span="16">{{key1}}</a-col>
                </a-col>
                <a-col :span="24">
                  <a-col :span="8">
                    <p class="descData">车辆：</p>
                  </a-col>
                  <a-col :span="16">{{key2}}</a-col>
                </a-col>
                <a-form-model-item label="交易金额(元)" prop="amount">
                  <a-input-number
                    v-model="form.amount"
                    :min="0"
                    :precision="2"
                    :max="999999999999.99"
                    style="width:100%"
                  />
                </a-form-model-item>
              </template>
              <template v-if="!isbusinessType1">
                <a-form-model-item label="加油卡卡号" prop="cardId">
                  <a-select
                    v-model="m"
                    show-search
                    :show-arrow="false"
                    :filter-option="false"
                    :default-active-first-option="false"
                    :not-found-content="null"
                    @search="handleOilCardChangeModal"
                    @select="handleOilCardSelect"
                  >
                    <a-select-option
                      v-for="(d) in oilCardLikeDataModal"
                      :key="d.cardId"
                    >{{ d.cardNo }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-col :span="24">
                  <a-col :span="8">
                    <p class="descData">车辆：</p>
                  </a-col>
                  <a-col :span="16">{{key3}}</a-col>
                </a-col>
                <a-col :span="24">
                  <a-col :span="8">
                    <p class="descData">司机：</p>
                  </a-col>
                  <a-col :span="16">{{key4}}</a-col>
                </a-col>
                <a-form-model-item label="交易金额(元)" prop="totalAmount">
                  <a-input-number
                    v-model="form.totalAmount"
                    :min="0"
                    :precision="2"
                    :max="999999999999.99"
                    @blur="totalAmountStr"
                    style="width:100%"
                  />
                </a-form-model-item>
                <a-form-model-item label="油量(L）" prop="oilVolume">
                  <a-input-number
                    v-model="form.oilVolume"
                    :min="0"
                    :precision="2"
                    @blur="oilVolumeStr"
                    style="width:100%"
                  />
                </a-form-model-item>
                <a-form-model-item label="单价(元/L）">
                  <!-- <a-input-number v-model="" :min='0' :precision="2" :max="999999999999.99" @blur="priceStr" style="width:100%"/> -->
                  {{form.price}}
                </a-form-model-item>
                <a-form-model-item label="当前里程数(km)" prop="mileage">
                  <a-input-number
                    v-model="form.mileage"
                    :min="0"
                    :max="999999999999.99"
                    :precision="2"
                    style="width:100%"
                  />
                </a-form-model-item>
                <a-form-model-item label="加油凭证">
                  <ud-upload @uploadFile="voucherPicsUpload" :length="10"></ud-upload>
                </a-form-model-item>
              </template>
            </a-col>
          </a-form-model>
        </a-col>
      </a-row>
    </a-modal>

    <!-- 加油消费详情 -->
    <a-modal
      :visible="visibleDetail"
      title="查看详情"
      :body-style="{padding: 0}"
      centered
      :footer="null"
      @cancel="handleCancelDetail"
    >
      <fuelCardConsumption v-if="visibleDetail" :id="detailId" />
    </a-modal>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import echartsLiquidfill from 'echarts-liquidfill'
import debounce from 'lodash/debounce'
import upload from '@/components/UpLoad'
import fuelCardConsumption from './fuelCardConsumption'
import { commonExport } from '@/api/request'
import { queryTruckOilCardDown } from '@/api'
import { queryTruckOilCardDetail, queryOilCardRecordList, rechargeTruckOilCard, addTruckOilInAndOutByCard } from '@/api/landCenter'
let queryColumn = null
const scrollArr = [{}, { x: 1500 }]
const fomrMessage = `必填项不能为空`

const createForm = () => ({
  cardId: null,
  amount: '',
  tractorId: '', // 牵引车id
  truckId: '', // 牵引车id
  driverId: '', // 司机id
  totalAmount: '', // 交易金额
  price: '--', // 单价(元/L）
  oilVolume: '', // 油量(L）
  mileage: '',
  voucherPics: '' // 加油凭证
})

export default {
  props: ['id'],
  data () {
    this.handleOilCardChange = debounce(this.handleOilCardChange, 800)
    this.handleOilCardChangeModal = debounce(this.handleOilCardChangeModal, 800)

    const column1 = [
      {
        title: '充值批次',
        dataIndex: 'batchNo'
      },
      {
        title: '加油卡',
        dataIndex: 'cardNo'
      },
      {
        title: '所属公司',
        dataIndex: 'custName'
      },
      {
        title: '车辆',
        dataIndex: 'truckNumber'
      },
      {
        title: '交易金额(元）',
        dataIndex: 'amount'
      },
      {
        title: '余额（元）',
        dataIndex: 'accountAmount'
      },
      {
        title: '日期',
        dataIndex: 'createTime',
        width: '120px'
      }
    ]

    const column2 = [
      {
        title: '加油批次',
        dataIndex: 'batchNo'
      },
      {
        title: '加油卡',
        dataIndex: 'cardNo',
        width: 180
      },
      {
        title: '车辆',
        dataIndex: 'truckNumber'
      },
      {
        title: '司机',
        dataIndex: 'driverName'
      },
      {
        title: '交易金额（元）',
        dataIndex: 'amount'
      },
      {
        title: '单价（元/L）',
        dataIndex: 'price'
      },
      {
        title: '油量（L）',
        dataIndex: 'oilVolume'
      },
      {
        title: '余额（元）',
        dataIndex: 'accountAmount'
      },
      {
        title: '当前里程数（km）',
        dataIndex: 'mileage'
      },
      {
        title: '日期',
        dataIndex: 'createTime',
        width: '180px'
      },
      {
        title: '操作',
        width: '110px',
        fixed: 'right',
        scopedSlots: { customRender: 'detail' }
      }
    ]

    queryColumn = [column1, column2]

    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      oilCardLikeData: [],
      oilCardLikeDataModal: [],
      truckOilCardInfo: {
        amount: '', // 当前余额
        rechargeAmount: '', // 充值总金额
        usedAmount: '', // 消费总金额
        usedOilVolume: ''
      },
      column: queryColumn[0],
      scroll: scrollArr[0],
      searchForm: {
        type: 1, // 1、油卡充值 2、加油消费
        cardId: '', // 加油卡id
        custName: '', // 所属公司
        truckNumber: '', // 车辆
        time1: '', // 开始时间
        time2: '' // 结束时间
      },
      loading: false,
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      tabIndex: 1, // 当前tab
      visible: false,
      // 添加记录
      businessType: 1,
      form: createForm(),
      key1: '--',
      key2: '--',
      key3: '--',
      key4: '--',
      formRules: {
        cardId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        amount: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        totalAmount: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        price: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        mileage: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        // tractorId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        // driverId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        oilVolume: [{ required: true, message: fomrMessage, trigger: 'blur' }]
      },
      m: '',
      // 查看油卡详情
      visibleDetail: false,
      detailId: null
    }
  },
  components: {
    'ud-upload': upload,
    fuelCardConsumption
  },
  created () {
  },
  computed: {
    isbusinessType1 () {
      return this.businessType === 1
    }
  },
  methods: {
    tabChange (i) {
      this.tabIndex = i
      this.searchForm.type = i
      this.tableData = []
      this.handleSubmit1()
    },
    onChangeDate (date, dateStr) {
      this.searchForm.time1 = dateStr[0]
      this.searchForm.time2 = dateStr[1]
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      // 数据区更新
      queryTruckOilCardDetail({ cardId: this.searchForm.cardId }).then(rsp => {
        this.truckOilCardInfo = rsp.data
        this.liquidFill(this.truckOilCardInfo.amount)
      })
      // 表格区更新
      let i = this.tabIndex
      this.column = queryColumn[i - 1]
      this.scroll = scrollArr[i - 1]
      this.loading = true
      queryOilCardRecordList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })
    },
    liquidFill (res) {
      let liquid = this.$echarts.init(
        document.getElementById('liquidFill')
      )
      let result
      if (res > 1000) {
        result = 0.5
      } else {
        result = 0.2
      }
      liquid.setOption({
        series: [
          {
            type: 'liquidFill',
            data: [result],
            radius: '95%',
            backgroundStyle: {
              color: '#fff',
              shadowColor: '#fff',
              shadowBlur: 0
            },
            itemStyle: {
              normal: {
                shadowBlur: 0
              }
            },
            outline: {
              show: true, // 是否显示轮廓 布尔值
              borderDistance: 5, // 外部轮廓与图表的距离 数字
              itemStyle: {
                borderColor: result === 0.5 ? '#1890FF' : '#f5222d', // 边框的颜色
                borderWidth: 2 // 边框的宽度
              }
            },
            color: result === 0.5 ? ['#1890FF'] : ['#f5222d'],
            label: {
              position: ['50%', '50%'],
              formatter: function (param) {
                return `当前余额(元)\n${res}`
              },
              fontSize: 14,
              color: '#666'
            }
          }
        ]
      })
    },
    handleOilCardChange (nameLike) { // 加油卡
      if (nameLike) {
        queryTruckOilCardDown({
          word: nameLike
        }).then(rsp => {
          this.oilCardLikeData = rsp.data
        })
      } else {
        this.oilCardLikeData = []
      }
    },
    handleOilCardChangeModal (nameLike = '') { // 加油卡modal
      queryTruckOilCardDown({
        word: nameLike
      }).then(rsp => {
        this.oilCardLikeDataModal = rsp.data
      })
    },
    handleOilCardSelect (cardId) {
      const t = this.oilCardLikeDataModal.filter(v => v.cardId === cardId)[0]
      if (t) {
        this.m = t.cardId
        this.form.cardId = t.cardId
        this.form.driverId = t.driverId
        this.form.tractorId = t.truckId
        this.form.truckId = t.truckId
        this.key1 = t.custName
        this.key2 = t.truckNumber
        this.key3 = t.truckNumber
        this.key4 = t.driverName
      }

      this.handleOilCardChangeModal()
    },
    exportExcel () {
      commonExport('/truckStock/exportOilCardRecordList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: queryColumn[this.tabIndex - 1]
      })
    },
    createRecord (id) {
      if (!this.$root._bc.createRecord) {
        this.$message.error('您无此权限！')
        return
      }
      // 初始化创建数据
      this.handleOilCardChangeModal()
      this.m = ''
      this.form = createForm()
      this.businessType = this.searchForm.type
      this.key1 = '--'
      this.key2 = '--'
      this.key3 = '--'
      this.key4 = '--'
      this.visible = true
    },
    handleAdd () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          if (this.isbusinessType1) {
            let { cardId, amount, truckId } = this.form
            rechargeTruckOilCard({ cardId, amount, truckId }).then(rsp => {
              this.$message.success('新增成功')
              this.handleCancel()
              this.handleSubmit()
            })
          } else {
            let { cardId, tractorId, driverId, totalAmount, price, oilVolume, voucherPics, mileage } = this.form
            addTruckOilInAndOutByCard({ cardId, tractorId, driverId, totalAmount, price, oilVolume, voucherPics, mileage }).then(rsp => {
              this.$message.success('新增成功')
              this.handleCancel()
              this.handleSubmit()
            })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    handleChangeBusinessType () {
      this.m = ''
      this.key1 = '--'
      this.key2 = '--'
      this.key3 = '--'
      this.key4 = '--'
      this.handleOilCardChangeModal()
      this.form = createForm()
    },
    voucherPicsUpload (urls) {
      this.form.voucherPics = urls
    },
    viewDetail (detailId) {
      this.detailId = detailId
      this.visibleDetail = true
    },
    handleCancelDetail () {
      this.visibleDetail = false
    },
    totalAmountStr () {
      const v = this.form.totalAmount
      if (this.form.oilVolume && v) this.form.price = Math.round(v / this.form.oilVolume * 100) / 100
      else this.form.price = '--'
    },
    oilVolumeStr () {
      const v = this.form.oilVolume
      if (this.form.totalAmount && v) this.form.price = Math.round(this.form.totalAmount / v * 100) / 100
      else this.form.price = '--'
    }
  },
  mounted () {
    this.$nextTick(() => {
      queryTruckOilCardDown({
        word: this.$route.query.cardNo
      }).then(rsp => {
        this.oilCardLikeData = rsp.data
        this.searchForm.cardId = this.id - 0
        this.handleSubmit()
      })
    })
  }
}
</script>

<style lang="less" scoped>
.card-container {
  background: #f0f2f5;
  overflow: hidden;
  padding: 24px;
  .ant-tabs-card {
    .ant-tabs-content {
      height: 120px;
      margin-top: -16px;
      .ant-tabs-tabpane {
        background: #fff;
        padding: 40px 24px 24px 24px;
      }
    }
    .ant-tabs-bar {
      border-color: #fff;
      .ant-tabs-tab {
        border-color: transparent;
        background: transparent;
      }
      .ant-tabs-tab-active {
        border-color: #fff;
        background: #fff;
      }
    }
  }
}
.computedData {
  height: 40px;
  line-height: 40px;
  margin-bottom: 24px;
  text-indent: 5px;
}

.descData {
  text-align: right;
  color: #000000d9;
}
</style>
<style>
.ant-card-body1 {
  background: #f9fcff;
  border: 1px #dbe3ff solid;
  padding: 24px 24px 16px 24px;
}
.caiG1 {
  background: url(../../../../static/images/ChuanbOil2.png) no-repeat right center;
}
.caiG2 {
  background: url(../../../../static/images/ChuanbOil1.png) no-repeat right center;
}
.ant-card-body1 .cgYoul {
  font-size: 40px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 400;
  margin-bottom: 0;
}
.ant-card-body1 .caiGou {
  margin-bottom: 0;
  line-height: 16px;
}
.ant-card-body1 .cgSale {
  margin-bottom: 0;
  line-height: 16px;
  border-top: 1px #dbe3ff solid;
  padding-top: 16px;
}
.ant-card-body1 .cgSale span {
  float: right;
  font-size: 18px;
  font-weight: bold;
}
</style>
